package com.zelo.blog.server.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;

/**
 * @description
 * @Auther zhanglu
 * @Date 2017/10/19 下午3:17
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private PreAuthenticatedProcessingFilter preAuthenticatedProcessingFilter;
    @Autowired
    private TokenProcessFilter tokenProcessFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()// 由于使用的是JWT，我们这里不需要csrf
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)// 基于token，所以不需要session
                .and().authorizeRequests().antMatchers("/","/static/**","/index.html").permitAll() //忽略静态资源
                .and().authorizeRequests().antMatchers(HttpMethod.PUT, "/secure/token").permitAll()// 只开放登录接口
                .anyRequest().authenticated()// 除上面外的所有请求全部需要鉴权认证
                .and()
                .addFilterBefore(tokenProcessFilter, PreAuthenticatedProcessingFilter.class)
                .addFilterAt(preAuthenticatedProcessingFilter, AbstractPreAuthenticatedProcessingFilter.class);
    }

    // 忽略静态资源的拦截
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers("/resources/public/**");
//    }
}
